<?php

namespace app\api\controller;

use app\common\controller\Api;

class Buycar extends Api
{
    protected $noNeedRight = ['*'];

    //加入购物车
    public function addcar()
    {
        $user = $this->auth->getUser();
        $good_id = input('good_id');
        $sku_id = input('sku_id');
        $num = input('num');
        $res = db('buycar')
            ->where([
                'user_id'=>$user->id,
                'products_id'=>$good_id,
                'productssku_id'=>$sku_id
            ])->find();
        if ($res){
            db('buycar')
                ->where('id',$res['id'])
                ->inc('num')
                ->update([
                   'updatetime'=>time()
                ]);
        }else{
            db('buycar')
                ->insert([
                    'createtime'=>time(),
                    'user_id'=>$user->id,
                    'products_id'=>$good_id,
                    'productssku_id'=>$sku_id,
                    'num'=>$num
                ]);
        }
        $this->success('加入成功');
    }
    //修改购物车数量
    public function editnum()
    {
        $car_id = input('car_id');
        $num = input('num');
        if ($num <= 0){
            db('buycar')
                ->where('id',$car_id)
                ->delete();
        }else{
            db('buycar')
                ->where('id',$car_id)
                ->update([
                    'updatetime'=>time(),
                    'num'=>$num
                ]);
        }
        $this->success('编辑成功');
    }
    //删除购物车
    public function delcars()
    {
        $car_ids = input('car_ids');
        db('buycar')
            ->where('id','in',$car_ids)
            ->delete();
        $this->success('删除成功');
    }
    //获取购物车列表
    public function getcarelist()
    {
        $user = $this->auth->getUser();
        $list = db('buycar')
            ->where([
                'user_id'=>$user->id
            ])
            ->order('id DESC')
            ->select();
        foreach ($list as &$value){
            $value['status'] = true;
            $value['stock_status'] = true;
            $value['good'] = db('products')
                ->field('id,name')
                ->where('id',$value['products_id'])
                ->find();
            if (!$value['good']){
                $value['status'] = false;
            }
            $value['sku'] = db('productssku')
                ->field('id,specificationvalues_names,image,price,del_price,vip_price,stock')
                ->where('id',$value['productssku_id'])
                ->find();
            if (!$value['sku']){
                $value['status'] = false;
            }
            if ($value['num'] > $value['sku']['stock']){
                //库存不足
                $value['stock_status'] = false;
            }
        }
        $this->success('ok',$list);
    }
}